<template>
  <div>
    <input type="file" ref="input" v-show="false" @change="onChange" />
    <el-dialog
      :visible.sync="isShowCurImage"
      title="图片剪裁"
      width="400px"
      :append-to-body="true"
    >
      <MmvCutImage
        :img="preview"
        v-if="isShowCurImage"
        @cancel="isShowCurImage = false"
        @submit="upload"
      ></MmvCutImage>
    </el-dialog>
    <div @click="onClick" style="display: inline-block">
      <slot></slot>
    </div>
    <slot name="tip"></slot>
    <!-- 预览图片 -->
    <div class="preview-list" v-if="preview.length>0">
      <div class="preview-wrap" >
        <el-image class="preview" :src="preview" fit="contain"></el-image>
        <el-button
          type="danger"
          icon="el-icon-delete-solid"
          @click="onClear"
        ></el-button>
      </div>
    </div>
  </div>
</template>

<script>
import MmvCutImage from './mmv-cut-Image.vue'
import { uploadAvatar } from '@/api/system/user'
export default {
  name: 'mmv-upload-image',
  components: {
    MmvCutImage,
  },
  props: {
    more: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isShowCurImage: false,
      preview: [],
    }
  },
  destroyed() {
    window.URL.revokeObjectURL(this.preview)
  },
  mounted() {
    console.log(this.more)
  },
  methods: {
    onClick() {
      this.$refs.input.click()
    },
    previewFun(image) {
      window.URL.revokeObjectURL(this.preview)
      this.preview = window.URL.createObjectURL(image)
    },
    onChange(evt) {
      const file = evt.target.files[0]
      evt.target.value = null
      this.previewFun(file)
      this.isShowCurImage = true
    },

    upload(blob) {
      this.previewFun(blob)
      this.isShowCurImage = false
      const url = this.preview
      let formData = new FormData()
      formData.append('avatarfile', blob)
      uploadAvatar(formData).then((res) => {
        this.$emit('upImg', res.imgUrl) // 这里指上传成功后拿到的url
      })
    },

    onClear() {
      this.preview = ''
      window.URL.revokeObjectURL(this.preview)
      this.$emit('upImg', '')
    },

    previewToUrl(url) {
      this.preview = url
    },
  },
}
</script>

<style lang="scss" scoped>
.preview-wrap {
  display: flex;
  align-items: flex-start;
}
.preview {
  width: 583px;
  height: 254px;
  border: 1px solid #ddd;
  margin-right: 10px;
}
</style>
